<template>
  <div class="image-upload">
    <el-upload
      list-type="picture-card"
      action="#"
      :limit="1"
      :file-list="fileList"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-change="handleChange"
      :before-upload="beforeUpload"
      :http-request="httpRequest"
      :class="{'is-show': isShow}"
    >
      <i class="el-icon-plus" />
    </el-upload>

    <el-dialog :visible.sync="dialogVisible" title="预览图片">
      <img width="100%" :src="ImageUrl" alt="">
    </el-dialog>

    <el-progress
      v-if="showProgress"
      :percentage="percentage"
      style="width: 180px;"
    />
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'

const cos = new COS({
  SecretId: 'AKID61h7IJ4aqrd9QRDj01nJabNuBDzWoqcA',
  SecretKey: 'KOCl59xVosgFZdS1MSIsDI8i27zcz7zb'
})

export default {
  name: 'image-upload',
  data () {
    return {
      dialogVisible: false,
      ImageUrl: '',
      fileList: [],
      currentFileUid: '',
      showProgress: false,
      percentage: 0
    }
  },
  computed: {
    isShow() {
      return this.fileList.length === 0 ? false : true
    }
  },
  methods: {
    handlePreview(file) {
      this.dialogVisible = true
      this.ImageUrl = file.url
    },
    handleRemove(file, fileList) {
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
    },
    handleChange(file, fileList) {
      this.fileList = fileList.map(item => item)
    },
    beforeUpload(file) {
      const arr = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if(!arr.includes(file.type)) {
        this.$message.warning('上传图片只能是 JPG、GIF、BMP、PNG 格式!')
        return false
      }

      const size = 1 * 1024 * 1024
      if(file.size >= size) {
         this.$message.warning('图片大小最大不能超过 1M!')
        return false
      }

      this.currentFileUid = file.uid
      this.showProgress = true
      return true
    },
    httpRequest (file) {
      cos.putObject({
        Bucket: 'test-16-1258617820', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-beijing',  /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: file.file.name,  /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        Body: file.file, // 上传文件对象
        onProgress: progressData => {
          this.percentage = progressData.percent * 100
        }
      }, (err, data) => {
        if (!err && data.statusCode === 200) {
          this.fileList = this.fileList.map(item => {
            if(item.uid === this.currentFileUid) {
              return { url: 'http://' + data.Location, upload: true }
            }
            return item
          })

          setTimeout(() => {
            this.showProgress = false
          }, 300)
        }
      })
    }
  }
}
</script>

<style lang="scss">
.is-show {
  .el-upload--picture-card {
    display: none;
  }
}
</style>
